package com.dongdongshop.shiro;

import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.TbUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;


//userrealm需要继承AuthorizingRealm,实现两个方法,认证和授权
public class UserRealm extends AuthorizingRealm {
    @DubboReference(check = false)
    private TbUserService userService;

    //授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return simpleAuthorizationInfo;
    }

    // 认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //提取表单提交的用户账号信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        TbUser user = userService.selectByUsername(token.getUsername());
        if(user == null){
            //如果账号不存在直接返回一个null,shiro会抛出UnknownAccountException未注册异常
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),user.getUsername());
    }
}
